# -*- coding: utf-8 -*-
#!flask/bin/python

import jieba as jb
import jieba.analyse as ja

from gensim.models import KeyedVectors

from flask import Flask, make_response, request, jsonify, abort

app = Flask(__name__)

model = KeyedVectors.load_word2vec_format('./data/hanlp-wiki-vec-zh.txt', binary=False)

stopwordsFile = './data/stop_word.txt'

def stopwordslist(filepath):
    stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]
    return stopwords

stop_words = stopwordslist(stopwordsFile)

@app.route('/', methods=['GET'])
def index():
    return "Hello, World!"

@app.route('/wordsvec', methods=['POST'])
def create_wordsvec():
    if not request.json or not 'content' in request.json or not 'text' in request.json:
        abort(400)
    try:
        cutCt = jb.cut(request.json['content'])
        cutText = jb.cut(request.json['text'])
        ct = []
        for w in cutCt:
            if w not in stop_words:
                try:
                    model[w]
                    ct.append(w)
                except Exception as e:
                    print(e)
        tt = []
        for w in cutText:
            if w not in stop_words:
                try:
                    model[w]
                    tt.append(w)
                except Exception as e:
                    print(e)
        return str(model.n_similarity(ct, tt))
    except Exception as e:
        raise e

@app.route('/keywords', methods=['POST'])
def create_keywords():
    if not request.json or not 'content' in request.json:
        abort(400)
    content = request.json['content']
    topK = int(len(content) / 16)
    ja.set_stop_words(stopwordsFile)
    tags = ja.extract_tags(content, topK=topK, withWeight=True)
    # print(tags)
    tags_index = []
    for t in tags:
        print(t)
        tags_index.append((t[0], content.index(t[0]), len(t[0]), t[1]))
    tags_index.sort(key=lambda el: el[1])
    # print(tags_index)
    tags_list = []
    i = 0
    for ts in tags_index:
        print(tags_list)
        if i == len(tags_index) - 1:
            break
        if i == 0:
            tags_list.append((ts[0], ts[1], ts[3]))
        if tags_index[i + 1][1] - (ts[1] + ts[2]) > 25 * ts[3]:
            tags_list.append((tags_index[i + 1][0], tags_index[i + 1][1], tags_index[i + 1][3]))
        else:
            # index = 0 if len(tags_list) == 0 else (len(tags_list) - 1)
            if len(tags_list) == 0:
                tags_list.append((content[ts[1]: tags_index[i + 1][1] + tags_index[i + 1][2]], ts[1], ts[3] + tags_index[i + 1][3]))
            else:
                tags_list[len(tags_list) - 1] = (tags_list[len(tags_list) - 1][0] + content[ts[1] + ts[2]: tags_index[i + 1][1] + tags_index[i + 1][2]], tags_list[len(tags_list) - 1][1], tags_list[len(tags_list) - 1][2] + tags_index[i + 1][3])
        i += 1
    tags_list.sort(key=lambda el: el[2], reverse=True)
    tags_list = tags_list[:3] if len(tags_list) > 3 else tags_list
    tags_list.sort(key=lambda el: el[1])
    return jsonify(tags_list)

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify({'error': 'Not found'}), 404)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8888)
